package com.yvan.periscope.controller;

import com.yvan.es.SearchAction;
import com.yvan.periscope.domain.HistogramTitleEnum;
import com.yvan.periscope.dto.request.HistogramReq;
import com.yvan.periscope.dto.request.SummaryReq;
import com.yvan.periscope.service.HistogramService;
import com.yvan.platform.JsonWapper;
import io.searchbox.client.JestClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者： lzw<br/>
 * 创建时间：2018-09-10 14:27 <br/>
 */
@Api(description = "总体指标概况")
@RequestMapping("/analytics")
@RestController
@Slf4j
public class SummaryController {

    private static final String PER_SUMMARY_INDEX = "per-summary-*";

    @Autowired
    private JestClient jestClient;

    @Autowired
    private HistogramService histogramService;

    @ApiOperation("汇总数据")
    @GetMapping("/summary_total_data.json")
    public Object summaryTotalData(HttpServletRequest request, HttpServletResponse response, SummaryReq summaryReq) throws IOException {
        summaryReq.defaultParam();
        SearchAction action = new SearchAction(log);
        action.index = PER_SUMMARY_INDEX;
        action.size = 0;
        action.query.filter.range("@timestamp", summaryReq.getMin().toString(), true, summaryReq.getMax().toString(), true);
        action.agg.sum("requestCount");
        action.agg.sum("esCount");
        action.agg.sum("rdsCount");
        action.agg.sum("jdbcExecuteCount");
        action.agg.max("concurrentMax");
        action.agg.sum("esResTotal");
        action.agg.sum("rdsResTotal");
        JsonWapper result = action.search(jestClient).getJsonWapper();
        Object requestCount = result.get("aggregations", "group_by@requestCount@requestCount");
        Object esCount = result.get("aggregations", "group_by@esCount@esCount");
        Object rdsCount = result.get("aggregations", "group_by@rdsCount@rdsCount");
        Object jdbcExecuteCount = result.get("aggregations", "group_by@jdbcExecuteCount@jdbcExecuteCount");
        Object concurrentMax = result.get("aggregations", "group_by@concurrentMax@concurrentMax");
        Object esResTotal = result.get("aggregations", "group_by@esResTotal@esResTotal");
        Object rdsResTotal = result.get("aggregations", "group_by@rdsResTotal@rdsResTotal");
        //summaryData是汇总数据
        Map<String, Object> summaryData = new HashMap<>();
        summaryData.put("requestCount", requestCount);
        summaryData.put("esCount", esCount);
        summaryData.put("rdsCount", rdsCount);
        summaryData.put("jdbcExecuteCount", jdbcExecuteCount);
        summaryData.put("concurrentMax", concurrentMax);
        summaryData.put("esResTotal", esResTotal);
        summaryData.put("rdsResTotal", rdsResTotal);
        response.addHeader("Q", action.build().toString(false));
        return summaryData;
    }

    @ApiOperation("表格数据")
    @GetMapping("/summary.json")
    public Object data(HttpServletRequest request, HttpServletResponse response, SummaryReq summaryReq) throws IOException {
        summaryReq.defaultParam();
        SearchAction action = new SearchAction(log);
        action.index = PER_SUMMARY_INDEX;
        action.size = 0;
        action.agg.DateHistogram("@timestamp", summaryReq.getGroupBy(), "yyyy-MM-dd HH:mm", summaryReq.getMin(), summaryReq.getMax())
                .sum("requestCount")
                .max("concurrentMax")
                .sum("rdsCount")
                .sum("rdsCostTotal")
                .max("rdsCostMax")
                .sum("rdsResTotal")
                .sum("esCount")
                .sum("esCostTotal")
                .max("esCostMax")
                .sum("esResTotal")
                .max("jdbcActivePeak")
                .max("jdbcPoolingPeak")
                .sum("jdbcExecuteCount")
                .sum("jdbcErrorCount")
                .sum("startTransactionCount")
                .sum("jdbcCommitCount")
                .sum("jdbcRollbackCount")
                .sum("jdbcExecuteTimeMillis")
                .sum("jdbcFetchRowCount")
                .sum("jdbcUpdateCount")
                .sum("notEmptyWaitMillis")
                .sum("botCount");
        JsonWapper result = action.search(jestClient).getJsonWapper();
        response.addHeader("Q", action.build().toString(false));
        return result;
    }

    @ApiOperation("直方图数据")
    @GetMapping("summary_histogram.json")
    public Object summaryHistogram(HttpServletRequest request, HttpServletResponse response, @Validated HistogramReq histogramReq) throws IOException {
        histogramReq.defaultParam();
        HistogramTitleEnum histogramTitleEnum = HistogramTitleEnum.getEnum("summary", histogramReq.getHistogramPrefix());
        if (histogramTitleEnum == null) {
            return null;
        }
        // response.addHeader("Q", action.build().toString(false));
        return histogramService.findHistogramFromPeriscope(
                PER_SUMMARY_INDEX,
                histogramReq.getHistogramPrefix(),
                histogramTitleEnum.getPartition(),
                histogramReq.getMin(),
                histogramReq.getMax(),
                histogramTitleEnum.getXAxisTitle(),
                histogramTitleEnum.getYAxisTitle()
        );
    }
}
